<template>
	<el-dialog title="角色设置" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
		<div class="treeMain">
			<el-tree ref="tree" node-key="id" :data="data.list" :props="data.props" show-checkbox default-expand-all="true"></el-tree>
		</div>
		<template #footer>
			<el-button @click="visible=false" >取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>
	import setting from './setting'
	import rSetting from './../role/setting'
	export default {
		emits: ['success', 'closed'],
		data() {
			return {
				visible: false,
				isSaveing: false,
				data: {
					list: [],
					checked: [],
					props: {
						label: (data)=>{
							return data.name
						}
					},
					roles: [],
					userId: 0
				}
			}
		},
		mounted() {
		},
		methods: {
			open(row){
				this.data.userId = row.id
				this.visible = true;
				this.loadRoles()
			},
			submit(){
				this.isSaveing = true;

				//选中的和半选的合并后传值接口
				var checkedKeys = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
				//console.log(checkedKeys)

				this.save(checkedKeys)

				// setTimeout(()=>{
				// 	this.isSaveing = false;
				// 	this.visible = false;
				// 	this.$message.success("操作成功")
				// 	this.$emit('success')
				// },1000)
			},
			async save(ids){
				var res = await setting.api.rolesSave.post({
					userId: this.data.userId,
					roleIds: ids
				});
				this.loading = false
				this.visible = false;
				if(res.code == setting.successCode){
					this.$message.success("操作成功")
				}else{
					this.$message.warning(res.message)
				}

			},
			async loadRoles(){
				let res = await rSetting.api.list.get({ pageIndex:1, pageSize: 2147483647 })
				if(res.code == setting.successCode){
					this.data.list = res.data
					if (res.data.length > 0) {
						this.loadUserRoles()
					}
				}else{
					this.$message.warning(res.message)
				}
			},
			async loadUserRoles(){
				let res = await setting.api.rolesList.get({ userId: this.data.userId })
				if(res.code == setting.successCode){
					let roleIds = res.data.map(item=>item.roleId)
					this.data.checked = roleIds	
					this.$nextTick(() => {
						let filterKeys = this.data.checked.filter(key => this.$refs.tree.getNode(key).isLeaf)
						this.$refs.tree.setCheckedKeys(filterKeys, true)
					})
				}else{
					this.$message.warning(res.message)
				}
			}
		}
	}
</script>

<style scoped>
	/* .treeMain {height:300px;overflow: auto;border: 1px solid #dcdfe6;margin-bottom: 10px;} */
	.treeMain {height:300px;overflow: auto; margin-bottom: 10px;}
</style>
